package com.xqboss.apps.controller.punch;

import cn.hutool.core.collection.CollUtil;
import com.xqboss.apps.convert.punch.PunchRuleConverter;
import com.xqboss.apps.domain.punch.PunchRule;
import com.xqboss.apps.service.punch.PunchRuleService;
import com.xqboss.apps.service.user.UserIdentityRankService;
import com.xqboss.apps.vo.punch.PunchRuleVo;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author Trent
 * @date 2023/8/15
 */
@Api(tags = {"打卡-打卡规则"})
@RestController
@RequestMapping("/punch/rule")
public class PunchRuleController extends BaseController {

    @Autowired
    private PunchRuleService punchRuleService;

    @Autowired
    private PunchRuleConverter punchRuleConverter;

    @Autowired
    private UserIdentityRankService userIdentityRankService;

    @ApiOperation("获取打卡规则")
    @GetMapping("get/{id}")
    public R<PunchRuleVo> getRule(@PathVariable("id")
                                  @ApiParam(value = "打卡规则ID", required = true)
                                  Long id) {
        PunchRule result = punchRuleService.getById(id);
        if(!result.getSaleable()){
            throw new ServiceException("打卡规则不存在！");
        }
        Objects.requireNonNull(result, "打卡规则不存在！");
        PunchRuleVo vo = punchRuleConverter.toVo(result);
        return R.ok(vo);
    }

    @ApiOperation("获取所有打卡规则列表")
    @GetMapping("list")
//    @Anonymous
    public R<List<PunchRuleVo>> getRuleList() {
        Long userId = getUserId();
        List<PunchRule> list = punchRuleService.getAllSaleableList();
        List<PunchRuleVo> vo = punchRuleConverter.toVoList(list);
        //不同身份拥有不同打卡次数
        if (CollUtil.isNotEmpty(vo)) {
            vo.forEach(item -> {
                Integer punchCount = userIdentityRankService.getUserRankIdentityPunchCount(userId, item.getPunchCount());
                item.setPunchCount(punchCount == null ? item.getPunchCount() : punchCount);
            });
        }
        return R.ok(vo, list);
    }
}
